﻿using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using ScannerApp.ScannerWebserviceWrapper;
using System.Text.RegularExpressions;

using ScannerApp.Utils;
using CodeBetter.Json;

namespace ScannerApp.Forms
{

    public partial class TransferStockForm : ScannerBaseForm
    {
        TransferStockOrderResult mOrder=null;
        private string currentBarCode = String.Empty;
        private int currentOrderIndex = 1;
        private int currentScanIndex = 1;
        private string shelfCode = String.Empty;

        public TransferStockForm()
        {
            InitializeComponent();
        }

        public override void Init()
        {
            base.Init();
            mCurrentStatus = ScanBarcodeStatus.ShelfCode;
            DispalyMessage("请扫描调出货位号");

        }
        public override void AssignControls()
        {
            this.lblMessage = this.labTitle;
            this.txtScanCode = this.txtScan;
            this.lblProductInfo = this.lblScanedInfo;
            this.lblHeaderInfo = this.lblHeader;
        }

        private void BindData(TransferStockOrderResult order, string message)
        {
            DispalyMessage(message);

            if (order != null)
            {
                mOrder = order;
                this.mScanProductOrder = order;

                this.dgOrder.TableStyles.Clear();
                this.dgOrder.TableStyles.Add(Utils.Utils.GetTableStyle(typeof(MergedTransferStockGoods)));
                //this.dgOrder.DataSource = Utils.Utils.ConvertListToDataTable(order.mergeProducts);

                RefreshOrderGrid(Utils.Utils.ConvertListToDataTable(order.mergeProducts), order.OrderPageIndex
                        , order.OrderTotalPage, new BaseParameter().pageSize, order.OrderTotalCount);


                this.dgScan.TableStyles.Clear();
                this.dgScan.TableStyles.Add(Utils.Utils.GetTableStyle(typeof(ScannedTransferStockGoods)));
               // this.dgScan.DataSource = Utils.Utils.ConvertListToDataTable(order.tempTransferInventoryList);

                RefreshScanGrid(Utils.Utils.ConvertListToDataTable(order.tempTransferInventoryList), order.ScanPageIndex
                             , order.ScanTotalPage, new BaseParameter().pageSize, order.ScanTotalCount);
            }
            else
            {
                mOrder = null;
                this.mScanProductOrder = null;
                this.dgOrder.DataSource = null;
                this.dgScan.DataSource = null;
            }
            

        }

        public override void HandleBarCode(string barCode)
        {
            try
            {
                base.HandleBarCode(barCode);

                currentBarCode = barCode;

                if (barCode.Equals(string.Empty))
                {
                    return;
                }
                
                if (mCurrentStatus == ScanBarcodeStatus.ShelfCode)
                {
                    shelfCode = barCode;
                    ScanShelfCode(barCode);
                }
                else if (mCurrentStatus == ScanBarcodeStatus.ProductCode)
                {
                    
                    //when the target shelf is not equal to the original shelf, trigger the transfer event. 
                    if (this.IsShelfcode(barCode, -1))
                    {
                        if (!barCode.Equals(this.mCurrentShelfCode))
                        {
                            ScanTargetShelf(barCode);                      
                        }
                        else
                        {
                            DispalyMessage("检测到目标货位与调出货位一致.");
                        }
                        return;
                    }
 

                    ScanProductCode(barCode, this.mOrder);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ScanShelfCode(string barCode)
        {
            TransferStockProductsParameter param = new TransferStockProductsParameter();
            param.TransferStockCode = barCode;
            param.searchType = 1;
            param.currentPage = this.currentOrderIndex;
            param.currentScanPage = this.currentScanIndex;


            String strResult = ScannerWebServiceProxy.Instance.transferStockOrder(Converter.Serialize(param));
            BaseResult<TransferStockOrderResult> result = Converter.Deserialize<BaseResult<TransferStockOrderResult>>(strResult);
            if (result.IsSucessful())
            {

                mOrderCode = barCode;
                this.mCurrentShelfCode = barCode;
                BindData(result.ReturnValue, "扫描调出货位成功,请扫描产品码或序列号.");
                mCurrentStatus = ScanBarcodeStatus.ProductCode;
            }
            else
            {
                BindData(null, "");
                DispalyMessage(result.getReturnCodeMessage());
            }
        }

        protected override void ScanQRCode(string QRcode)
        {
            Regex reg = new Regex("^[0-9a-zA-Z]+$");
            if (QRcode.Length < 15 || QRcode.Length > 20 || !reg.IsMatch(QRcode))
            {
                DispalyMessage("扫描序列号格式不正确.");
                return;
            }

            if (this.mOrder.IsRepeatedScan(QRcode))
            {
                DispalyMessage("此码已经被扫描过了");
                return;
            }

            this.mCurrentProductQR = QRcode;

            TransferStockSingleProductParameter param = new TransferStockSingleProductParameter();
            param.TransferStockCode = this.mOrderCode;
            param.ProductCode = QRcode;
            param.Quantity = 1;
            param.currentPage = this.currentOrderIndex;
            param.currentScanPage = this.currentScanIndex;
            param.searchType = 1;


            string strResult = ScannerWebServiceProxy.Instance.transferStockSingleProduct(Converter.Serialize(param));
            BaseResult<TransferStockOrderResult> result = Converter.Deserialize<BaseResult<TransferStockOrderResult>>(strResult);
            if (result.IsSucessful())
            {
                BindData(result.ReturnValue, "已扫描成功.请继续扫描产品或者目标货位.");
            }
            else
            {
                DispalyMessage(result.getReturnCodeMessage());
            }
        }

        protected override void ScanProductWithQuantity(string productCode, string lot, float quantity)
        {

            TransferStockSingleProductParameter param = new TransferStockSingleProductParameter();
            param.TransferStockCode = this.mOrderCode;
            param.InventoryCode = productCode;
            param.Lot = lot;
            param.Quantity = quantity;
            param.searchType = 3;
            param.currentPage = this.currentOrderIndex;
            param.currentScanPage = this.currentScanIndex;

            string strResult = ScannerWebServiceProxy.Instance.transferStockSingleProduct(Converter.Serialize(param));
            BaseResult<TransferStockOrderResult> result = Converter.Deserialize<BaseResult<TransferStockOrderResult>>(strResult);
            if (result.IsSucessful())
            {
                BindData(result.ReturnValue, "已扫描成功,请继续扫描产品或者目标货位.");
            }
            else
            {
                DispalyMessage(result.getReturnCodeMessage());
            }
        }

        protected void ScanTargetShelf(string barcode)
        {
            if (this.mOrder.tempTransferInventoryList.Count == 0)
            {
                DispalyMessage("没有扫描任何产品.");
                return;
            }

            TransferStockPutOnShelfParameter param = new TransferStockPutOnShelfParameter();
            param.TransferStockCode = this.mOrderCode;
            param.ShelfCode = barcode;

            string strResult = ScannerWebServiceProxy.Instance.transferStockPutOnShelf(Converter.Serialize(param));
            BaseResult<TransferStockOrderResult> result = Converter.Deserialize<BaseResult<TransferStockOrderResult>>(strResult);
            if (result.IsSucessful())
            {
                BindData(result.ReturnValue, "已生成移库单.请扫描新的移出库位.");
                this.mCurrentStatus = ScanBarcodeStatus.ShelfCode;
            }
            else
            {
                DispalyMessage(result.getReturnCodeMessage());
            }
        }



        private void EnablingFinishMenu()
        {
            if (this.mOrder.HasOrderFinished())
            {
                if (!this.mnuOperate.MenuItems.Contains(this.menuComplete))
                {
                    this.mnuOperate.MenuItems.Add(this.menuComplete);
                }
            }
            else
            {
                if (this.mnuOperate.MenuItems.Contains(this.menuComplete))
                {
                    this.mnuOperate.MenuItems.Remove(this.menuComplete);
                }
            }
        }

        private void txtScan_KeyPress(object sender, KeyPressEventArgs e)
        {
            this.HandleKeyPress(e);
        }

        private void menuComplete_Click(object sender, EventArgs e)
        {

        }

        private void menuDelete_Click(object sender, EventArgs e)
        {
            if (this.dgOrder.CurrentRowIndex < 0)
            {
                MessageBox.Show("请选择一条已扫描的记录");
            }
            else
            {
                int num = this.dgOrder.CurrentRowIndex;
                string productCode = this.mOrder.tempTransferInventoryList[num].id.ToString();
                TransferStockSingleProductParameter param = new TransferStockSingleProductParameter();
                param.TransferStockCode = this.mOrderCode;
                param.ProductCode = productCode;
                param.searchType = 1;
                param.currentPage = this.currentOrderIndex;
                param.currentScanPage = this.currentScanIndex;

                string strResult = ScannerWebServiceProxy.Instance.transferStockCancelSingleProduct(Converter.Serialize(param));
                BaseResult<TransferStockOrderResult> result = Converter.Deserialize<BaseResult<TransferStockOrderResult>>(strResult);
                if (result.IsSucessful())
                {
                    BindData(result.ReturnValue, "已取消选定数据");
                }
                else
                {
                    DispalyMessage("产品未能取消");
                }

            }
        }

        private void menuClear_Click(object sender, EventArgs e)
        {
            if (mOrderCode == string.Empty)
            {
                return;
            }
            TransferStockProductsParameter param = new TransferStockProductsParameter();
            param.TransferStockCode = this.mOrderCode;
            param.searchType = 1;
            param.currentPage = this.currentOrderIndex;
            param.currentScanPage = this.currentScanIndex;

            String strResult = ScannerWebServiceProxy.Instance.transferStockClearScanedProducts(Converter.Serialize(param));
            BaseResult<TransferStockOrderResult> result = Converter.Deserialize<BaseResult<TransferStockOrderResult>>(strResult);
            if (result.IsSucessful())
            {
                BindData(result.ReturnValue, "已清空扫描的产品");
            }
            else
            {
                DispalyMessage("清空已扫描产品失败");
            }
        }

        private void menuRefresh_Click(object sender, EventArgs e)
        {
            if (mOrderCode == string.Empty)
            {
                return;
            }
            TransferStockProductsParameter param = new TransferStockProductsParameter();
            param.TransferStockCode = this.mOrderCode;
            param.searchType = 1;
            param.currentPage = this.currentOrderIndex;
            param.currentScanPage = this.currentScanIndex;

            String strResult = ScannerWebServiceProxy.Instance.transferStockOrder(Converter.Serialize(param));
            BaseResult<TransferStockOrderResult> result = Converter.Deserialize<BaseResult<TransferStockOrderResult>>(strResult);
            if (result.IsSucessful())
            {
                BindData(result.ReturnValue, "数据已刷新");
            }
        }

        private void ClearGridData()
        {
            DisplayScannedCode("");
            DispalyMessage("");
            this.currentOrderIndex = 1;
            this.currentScanIndex = 1;
            this.dgOrder.DataSource = null;
            this.dgScan.DataSource = null;
            lbOrderPagination.Text = String.Empty;
            lbScanPagination.Text = String.Empty;
            btnNext.Visible = false;
            btnPrev.Visible = false;
            btnScanNext.Visible = false;
            btnScanPrev.Visible = false;

        }

        private void RefreshOrderGrid(DataTable dataTable, int pageIndex, int totalPage, int pageSize, int totalCount)
        {
            this.dgOrder.DataSource = dataTable;
            if (this.currentOrderIndex == 1)
            {
                this.btnPrev.Enabled = false;
            }
            else
            {
                this.btnPrev.Enabled = true;
            }

            if (this.currentOrderIndex == totalPage)
            {
                this.btnNext.Enabled = false;
            }
            else
            {
                this.btnNext.Enabled = true;
            }
            this.lbOrderPagination.Text = "第" + pageIndex + "/" + totalPage + "页," + "每页" + pageSize + "条," + "共" + totalCount + "条";
            this.btnPrev.Visible = true;
            this.btnNext.Visible = true;
        }

        private void RefreshScanGrid(DataTable dataTable, int pageIndex, int totalPage, int pageSize, int totalCount)
        {
            this.dgScan.DataSource = dataTable;

            if (this.currentScanIndex == 1)
            {
                this.btnScanPrev.Enabled = false;
            }
            else
            {
                this.btnScanPrev.Enabled = true;
            }

            if (this.currentScanIndex == totalPage)
            {
                this.btnScanNext.Enabled = false;
            }
            else
            {
                this.btnScanNext.Enabled = true;
            }
            this.lbScanPagination.Text = "第" + pageIndex + "/" + totalPage + "页," + "每页" + pageSize + "条," + "共" + totalCount + "条";
            this.btnScanPrev.Visible = true;
            this.btnScanNext.Visible = true;
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            this.currentOrderIndex++;
            dbTempTransferScannerOrderPagination();

        }

        private void btnPrev_Click(object sender, EventArgs e)
        {
            this.currentOrderIndex--;
            dbTempTransferScannerOrderPagination();
        }

        private void btnScanPrev_Click(object sender, EventArgs e)
        {
            this.currentScanIndex--;
            tempDespatchListScannerPagination();

        }

        private void btnScanNext_Click(object sender, EventArgs e)
        {
            this.currentScanIndex++;
            tempDespatchListScannerPagination();

        }

        private void dbTempTransferScannerOrderPagination()
        {
            try
            {
                BaseResult<TransferStockOrderResult> result = null;
                
                TransferStockProductsParameter param = new TransferStockProductsParameter();
                param.TransferStockCode = shelfCode;
                param.searchType = 2;
                param.currentPage = this.currentOrderIndex;
                param.currentScanPage = this.currentScanIndex;

                String strResult = ScannerWebServiceProxy.Instance.transferStockOrder(Converter.Serialize(param));
                result = Converter.Deserialize<BaseResult<TransferStockOrderResult>>(strResult);

                if (result != null && result.IsSucessful())
                {
                    this.currentOrderIndex = result.ReturnValue.OrderPageIndex;
                    RefreshOrderGrid(Utils.Utils.ConvertListToDataTable(result.ReturnValue.mergeProducts), result.ReturnValue.OrderPageIndex
                     , result.ReturnValue.OrderTotalPage, param.scanPageSize, result.ReturnValue.OrderTotalCount);
                }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void tempDespatchListScannerPagination()
        {
            try
            {
                try
                {
                    BaseResult<TransferStockOrderResult> result = null;

                    TransferStockProductsParameter param = new TransferStockProductsParameter();
                    param.TransferStockCode = shelfCode;
                    param.searchType = 3;
                    param.currentPage = this.currentOrderIndex;
                    param.currentScanPage = this.currentScanIndex;

                    String strResult = ScannerWebServiceProxy.Instance.transferStockOrder(Converter.Serialize(param));
                    result = Converter.Deserialize<BaseResult<TransferStockOrderResult>>(strResult);

                    if (result != null && result.IsSucessful())
                    {
                        this.mOrder.tempTransferInventoryList = result.ReturnValue.tempTransferInventoryList;
                        this.currentScanIndex = result.ReturnValue.ScanPageIndex;
                        RefreshScanGrid(Utils.Utils.ConvertListToDataTable(result.ReturnValue.tempTransferInventoryList), result.ReturnValue.ScanPageIndex
                         , result.ReturnValue.ScanTotalPage,param.scanPageSize, result.ReturnValue.ScanTotalCount);                       
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}